package com.craftplay.interceptor;

import com.craftplay.dao.UserMapper;
import com.craftplay.dao.UserTicketMapper;
import com.craftplay.model.HostHolder;
import com.craftplay.model.User;
import com.craftplay.model.UserTicket;
import com.craftplay.util.UserAgentUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class CookieInterceptor implements HandlerInterceptor {

    @Autowired
    UserTicketMapper userTicketMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    HostHolder hostHolder;

    @Autowired
    private Environment env;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if (env.getProperty("isDebug").equals("true")) {
            User user = userMapper.selectByPrimaryKey(6);
            hostHolder.setUser(user);
            return true;
        }
        if (!UserAgentUtil.isWechat(httpServletRequest)) {
            User user = userMapper.selectByPrimaryKey(-1);
            hostHolder.setUser(user);
            return true;
        }
        String ticket = null;
        if (httpServletRequest.getCookies() != null) {
            for (Cookie cookie : httpServletRequest.getCookies()) {
                if (cookie.getName().equals("ticket")) {
                    ticket = cookie.getValue();
                    break;
                }
            }
        }

        if (ticket != null) {
            UserTicket userTicket = userTicketMapper.selectByTicket(ticket);
            if (userTicket == null || userTicket.getExpired().before(new Date()) || userTicket.getStatus() != 0) {
                return true;
            }
            User user = userMapper.selectByPrimaryKey(userTicket.getUserId());
            if (user.getSubscribe() != 1) {
                user = userMapper.selectByPrimaryKey(-1);
                hostHolder.setUser(user);
            } else {
                hostHolder.setUser(user);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        hostHolder.clear();
    }

}
